<template>
    <!--配合specTree.vue使用-->
    <view class="spec-tree-item">
        <view v-if="noLast">
            <!-- 不是最后一组规格 -->
            <view class="sku-item">
                <view class="sku-item-title"><text>{{ getTreeData[0].AttributeName }}：</text></view>
                <view class="sku-item-select">
                    <view v-for="(item, index) in getTreeData" :key="index" class="btn btn-gray-fill"
                        :class="activeIndex === index ? 'btn-success-fill' : ''" @click="_clickEvent(item, index)">
                        {{ item.ValueStr }}
                    </view>
                </view>
            </view>
            <view v-if="getTreeData[0].ProductAttrList && getTreeData[0].ProductAttrList.length > 0"
                class="spec-sub-tree">
                <!--SpecTreeItem组件中调用SpecTreeItem组件-->
                <!-- 根据上级规格的数量创建多个item，根据上级规格选中的项来显示对应的下级规格栏-->
                <view v-for="(item, index) in getTreeData" v-show="activeIndex === index" :key="index">
                    <SpecTreeItem :tree-data="item.ProductAttrList" :active-id="activeId" :min-num="minNum"
                        :limit-buy="limitBuy" :data="data" :unitActiveIndex="unitActiveIndex"
                        @treeClickEvent="treeClickEvent" @setCarListFunc="setCarListFunc" :tempType="tempType"
                        :addNum="addNum" />
                </view>
            </view>
        </view>
        <view v-else>
            <!-- 是最后一组规格 -->
            <view class="num-title" v-if="getTreeData[0]">
                <text class="title-label" v-if="getTreeData[0].AttributeName">{{ getTreeData[0].AttributeName }}</text>
                <text class="title-label">价格</text>
                <!-- <text class="title-label">零售价</text> -->
                <text class="title-label">库存</text>
                <text class="buy-num">购买数量</text>
            </view>
            <!-- 根据上级规格的数量创建多个item，根据上级规格选中的项来显示对应的下级规格栏-->
            <!-- 				<view v-for="(item,index) in getTreeData" :key="index" class="num-item" v-if="item.SkuModel">
					<text class="num-value" v-if="item.ValueStr && getTreeData[0] && getTreeData[0].AttributeName">{{ item.ValueStr }}<text class="itemRemark" v-if="item.SkuModel.Remark">{{item.SkuModel.Remark}}</text v-if=""></text>
					<text class="num-value" >{{ item.SkuModel.ProductUnitPrice.Price }}</text>
					<text class="num-value" v-if="item.SkuModel.Stock > 0">{{ item.SkuModel.Stock }}</text>
					<text class="num-value num-value-main" v-else @click="inquire(item)">查询库存</text>
					<view class="input-number-box">
						<text class="btn-minus" :class="item.Amount<=0?'color-shadow':''"
							@click="changeAmount(item, item.Amount, item.Stock, -1, minNum, item.Ratio, limitBuy,item.AddNum)">-</text>
						<view class="btn-input-box">
							<input v-model="item.Amount" type="number" class="btn-input"
								@blur="changeAmount(item, item.Amount, item.Stock, 0, minNum, item.Ratio, limitBuy,item.AddNum)"> -->
            <view v-for="(item, index) in getTreeData" :key="index" v-if="item.SkuModel">
                <view v-if="item.SkuModel.ProductUnitPrice.IsCustomized" class="num-item">
                    <text>{{ item.ValueStr }}定制</text>
                    <text>{{ item.Ratio }}{{ actions[0].unitName }}/{{ actions[unitActiveIndex].unitName }}</text>
                    <view class="input-number-box">
                        <text class="btn-minus" :class="item.Ratio <= 0 ? 'color-shadow' : ''"
                            @click="changeRatio(item, item.Ratio, -1)">-</text>
                        <view class="btn-input-box">
                            <input v-model="item.Ratio" type="number" class="btn-input"
                                @blur="changeRatio(item, item.Ratio, 0)" />
                        </view>
                        <text class="btn-plus" @click="changeRatio(item, item.Ratio, 1)">+</text>
                    </view>
                </view>
                <view class="num-item">
                    <!-- <view v-if="item.SkuModel.ProductUnitPrice.IsCustomized"></view> -->
                    <text class="num-value" v-if="item.ValueStr && getTreeData[0] && getTreeData[0].AttributeName">{{
                        item.ValueStr
                    }}<text class="itemRemark" v-if="item.SkuModel.Remark">{{ item.SkuModel.Remark }}</text></text>
                    <text class="num-value">{{ item.SkuModel.ProductUnitPrice.Price }}</text>
                    <!-- <text class="num-value" >{{ item.SkuModel.ProductUnitPrice.RetailPrice }}</text> -->
                    <text class="num-value" v-if="item.SkuModel.Stock > 0">{{ item.SkuModel.Stock }}</text>
                    <text class="num-value num-value-main" v-else @click="inquire(item)">查询库存</text>
                    <view v-if="selectType == 4" style="width: 234rpx; text-align: center;">
                        <button class="btn btn-main btn-select-spec" @click="changeAmount(
                            item,
                            item.Amount,
                            item.Stock,
                            1,
                            minNum,
                            item.Ratio,
                            limitBuy,
                            item.AddNum,
                        )" style="font-size: 24rpx;">
                            加入清单
                        </button>
                    </view>
                    <view class="input-number-box" v-else>
                        <text class="btn-minus" :class="item.Amount <= 0 ? 'color-shadow' : ''" @click="
                            changeAmount(
                                item,
                                item.Amount,
                                item.Stock,
                                -1,
                                minNum,
                                item.Ratio,
                                limitBuy,
                                item.AddNum,
                            )
                            ">-</text>
                        <view class="btn-input-box">
                            <input v-model="item.Amount" type="number" class="btn-input" @blur="
                                changeAmount(
                                    item,
                                    item.Amount,
                                    item.Stock,
                                    0,
                                    minNum,
                                    item.Ratio,
                                    limitBuy,
                                    item.AddNum,
                                )
                                " />
                        </view>
                        <text class="btn-plus" @click="
                            changeAmount(
                                item,
                                item.Amount,
                                item.Stock,
                                1,
                                minNum,
                                item.Ratio,
                                limitBuy,
                                item.AddNum,
                            )
                            ">+</text>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { mapMutations, mapGetters } from "vuex"
import SpecTreeItem from "@/components/product/spec-tree-item.vue"

import utilsOld from "@/utils/utilsOld.js"
import { getAmountInTempCart } from "@/utils/tempCartUtil.js"
import { getProductDisplayForCache } from "@/utils/appInit.js"
export default {
    name: "SpecTreeItem",
    components: {
        SpecTreeItem,
    },
    props: {
        data: {
            // 数据
            type: Object,
        },
        treeData: {
            type: Array,
            default() {
                return []
            },
        },
        activeId: {
            type: Number,
            default: -1,
        },
        minNum: {
            type: Number,
            default: 0,
        },
        limitBuy: {
            type: Number,
            default: 0,
        },
        isSingle: {
            type: Boolean,
            default: false,
        },
        tempType: {
            type: Number,
            default: 0,
        },
        addNum: {
            type: Number,
            default: 1,
        },
        unitActiveIndex: {
            // 选中单位
            type: Number,
            default: 0,
        },
        selectType: {
            type: [Number, String],
            default: 0,
        }
    },
    watch: {
        //监听购物车数据
        getCartData(data) { },
        //监听临时购物车数据
        getTempCartData(data) { },
        //代客下单购物车数据
        getValetCartData(data) { },
        unitActiveIndex(newVal, oldVal) {
            if (newVal != oldVal) {
                this.unitActiveIndex = newVal
            }
        },
    },
    computed: {
        ...mapGetters(["getCartData", "getTempCartData", "getValetCartData"]),
    },
    data() {
        return {
            activeIndex: -1,
            numValue: 0,
            noLast: false,
            getTreeData: [],
            actions: [],
        }
    },
    mounted() {
        this.getTreeData = this.treeData
        this.noLast =
            this.getTreeData &&
            this.getTreeData.length > 0 &&
            this.getTreeData[0].ProductAttrList &&
            this.getTreeData[0].ProductAttrList.length > 0
        if (!this.noLast) {
            this.getTreeData.forEach((e) => {
                this.getCurrentNum(e)
            })
        }
        console.log(55)
        console.log(this.tempType)
        // 多单位(如米/支)用于一开始显示
        this.actions = []
        if (this.data.ProductUnitList && this.data.ProductUnitList.length > 1) {
            this.data.ProductUnitList.forEach((element) => {
                this.actions.push({
                    text: element.Title,
                    ratio: element.Ratio,
                    unitName: element.UnitName,
                    unitId: element.UnitId,
                })
            })
        }
        this.$forceUpdate()
    },
    methods: {
        getCurrentNum(item) {
            if (this.tempType == 0) {
                this.getCartData.forEach((e) => {
                    if (e.ProductId == item.ProductId) {
                        e.SubItems.forEach((sub) => {
                            if (sub.SkuId == item.SkuId && item.UnitId == sub.UnitId) {
                                item.Amount = sub.Amount
                            }
                        })
                    }
                })
            } else if (this.tempType == 1) {
                let amount = getAmountInTempCart(item)
                item.Amount = amount
            } else if (this.tempType == 2) {
                this.getValetCartData.forEach((e) => {
                    if (e.ProductId == item.ProductId) {
                        e.SubItems.forEach((sub) => {
                            if (sub.SkuId == item.SkuId && item.UnitId == sub.UnitId) {
                                item.Amount = sub.Amount
                            }
                        })
                    }
                })
            }
            if (item.Amount > 0) {
                this.setCarListFunc(item)
            }
        },
        // 多单位定制
        changeRatio(item, num, type) {
            console.log(item, num, type, "item,num,type")
            if (type != 0) {
                item.Ratio = Number(num) + Number(type)
                if (type == -1) {
                    if (num > 1) {
                        item.Ratio = Number(num) - 1
                    } else {
                        item.Ratio = 1
                    }
                }
            } else {
                if (num > 0) {
                    item.Ratio = Number(num)
                    this.$forceUpdate()
                } else {
                    item.Ratio = 1
                    this.$forceUpdate()
                }
            }
            this.$forceUpdate()
        },
        //获取购买数量
        getAmount(num) {
            return num
        },
        // 节点点击事件
        _clickEvent(item, index) {
            this.activeIndex = index

            // 如果有传递事件函数，则调用事件函数并传递当前节点数据及组件
            this.treeClickEvent(item, index)
        },
        changeAmount(item, num, stock, type, minNum, UnitRatio, LimitBuy, addNum) {
            addNum = this.addNum
            const _oldAmount = item.Amount
            num = Number(num)
            addNum = UnitRatio && UnitRatio == 1 ? addNum : 1
            addNum = addNum == 0 ? 1 : addNum
            if (getProductDisplayForCache().NoCheckStock) {
                if (type != 0) {
                    item.Amount = num + Number(type) * addNum
                    if (type == -1 && item.Amount * UnitRatio < minNum) {
                        item.Amount = 0
                    } else if (item.Amount * UnitRatio < minNum) {
                        minNum = parseInt(minNum / UnitRatio) + (minNum % UnitRatio > 0 ? 1 : 0)
                        let addN = minNum % addNum
                        let newNum = utilsOld.getMaxNum(minNum, addNum, addN)
                        item.Amount = newNum
                    }
                } else {
                    if (num > 0) {
                        let addN = num % addNum
                        let newNum = utilsOld.getMaxNum(num, addNum, addN)
                        item.Amount = newNum
                        if (item.Amount * UnitRatio < minNum) {
                            minNum = parseInt(minNum / UnitRatio) + (minNum % UnitRatio > 0 ? 1 : 0)
                            let addN = minNum % addNum
                            let newNum = utilsOld.getMaxNum(minNum, addNum, addN)
                            item.Amount = newNum
                        }
                    } else {
                        item.Amount = 0
                    }
                }

                if (item.Amount < 0) {
                    item.Amount = 0
                }
            } else {
                utilsOld.changeAmountNew(item, num, stock, type, minNum, UnitRatio, LimitBuy, addNum)
            }
            if (item.Amount > 0) {
                item.Amount = item.Amount.toFixed(item.NumDigits)
            }
            item.Amount = Number(item.Amount)
            if (_oldAmount !== item.Amount || type === 0) {
                console.log(item)
                const _obj = {}
                _obj.ProductId = item.ProductId
                _obj.Amount = item.Amount
                _obj.SkuId = item.SkuId
                _obj.UnitId = item.UnitId
                _obj.UnitName = item.UnitName
                _obj.ValueId = item.ValueId
                _obj.Ratio = item.Ratio
                // _obj.AttributeName = item.AttributeName
                // 同步多规格要加入购物车的数据
                this.setCarListFunc(_obj)
                this.$forceUpdate()
            }
        },
        setCarListFunc(obj) {
            this.$emit("setCarListFunc", obj)
            this.$forceUpdate()
        },
        treeClickEvent(item, index) {
            this.$emit("treeClickEvent", item, index)
        },
        inquire(item) {
            this.$emit("inquire", item)
        },
    },
}
</script>
<style lang="scss" scoped>
.spec-tree-item {
    .sku-item {
        display: flex;
        flex-direction: column;
        margin-bottom: 20rpx;

        .sku-item-title {}

        .sku-item-select {
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            margin: 20rpx 0;

            .btn {
                display: block;
                min-width: 100rpx;
                height: 60rpx;
                line-height: 60rpx;
                font-size: 26rpx;
                border-radius: $border-radius-10;
                margin-right: 10px;
                margin-bottom: 10px;
                margin-right: 20rpx;
            }
        }
    }

    .num-title {
        display: flex;
        flex-direction: row;
        margin-bottom: 20rpx;
        border-top: solid 1rpx $app-color-input-bg;
        padding-top: $app-page-padding;

        .title-label {
            display: flex;
            flex: 1;
        }

        .buy-num {
            display: flex;
            width: 234rpx;
            justify-content: center;
        }
    }
}

.num-item {
    display: flex;
    flex-direction: row;
    margin-bottom: 20rpx;
    align-items: center;

    text {
        display: flex;
        flex: 1;
    }
}

.num-value-main {
    color: $app-color-main;
}

.itemRemark {
    font-size: 20rpx;
    color: #999;
    display: block;
}

.btn-select-spec {
    height: 52rpx;
    border-radius: 100rpx;
    font-size: $font-size-30;
}
</style>
